import 'package:flutter/material.dart';

class SegmentBarView extends StatefulWidget {
  List<String> datas;
  Function(String) onSelected;
  int defaultIndex = 0;

  SegmentBarView({@required this.datas, this.onSelected, this.defaultIndex});

  @override
  _SegmentBarViewState createState() => _SegmentBarViewState();
}

class _SegmentBarViewState extends State<SegmentBarView> {
  List<String> sdkLists;
  String selectItem;

  @override
  void initState() {
    super.initState();
    sdkLists = widget.datas;
    selectItem = sdkLists[widget.defaultIndex];
  }

  @override
  Widget build(BuildContext context) {
    return SingleChildScrollView(
      scrollDirection: Axis.horizontal,
      child: Container(
        padding: EdgeInsets.only(left: 10, right: 10),
        child: Row(
          children: _buildSegments(sdkLists),
        ),
      ),
    );
  }

  _buildSegments(List list) {
    if (list == null) {
      return Container();
    }
    List<Widget> items = List();
    list.forEach((item) {
      if (item != null) {
        items.add(Container(
          padding: EdgeInsets.only(top: 8, bottom: 8),
          child: _buildItem(item),
        ));
      }
    });
    return items;
  }

  _buildItem(String item) {
    if (selectItem == item) {
      return Container(
        height: 34,
        child: RaisedButton(
          shape: RoundedRectangleBorder(
//            borderRadius: BorderRadius.circular(15)
              ),
          color: Color(0xFF00A6DE),
          onPressed: () {},
          child: Text(
            item,
            style: TextStyle(color: Colors.white),
          ),
        ),
      );
    } else {
      return Container(
        height: 34,
        child: OutlineButton(
          borderSide: BorderSide(color: Color(0xFFcccccc), width: 0.5),
          onPressed: () {
            updateGroupValue(item);
          },
          child: Text(item),
        ),
      );
    }
  }

  updateGroupValue(String item) {
    if (item == selectItem) {
      return;
    } else {
      selectItem = item;
      widget.onSelected(selectItem);
      setState(() {});
    }
  }
}
